package com.hustzp.com.xichuangzhu.me;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.dao.WorksDao;
import com.hustzp.com.xichuangzhu.poetry.model.Works;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by Administrator on 2016/6/8.
 */
public class LikeWorksFragment extends Fragment {

    View rootView = null;

    private PtrFrameLayout worksPtrFrameLayout;
    private LoadMoreListViewContainer worksContainer;
    private List<Works> works = new ArrayList<>();
    private ListView worksListView;
    private WorksAdapter worksAdapter;

    private int pageIndex = 1;
    private int pageSize = 15;

    private Map<Integer, AVObject> worksObjs = new HashMap<>();
    private boolean isDelMode;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_like_works, container, false);
            initViews();
        }

        return rootView;
    }

    private void initViews() {
        isDelMode = getArguments().getBoolean("isDelMode");

        worksListView = (ListView) rootView.findViewById(R.id.list_view_work);
        worksAdapter = new WorksAdapter(works);
        worksListView.setAdapter(worksAdapter);

        worksPtrFrameLayout = (PtrFrameLayout) rootView.findViewById(R.id.ptr_frame_work);

        worksPtrFrameLayout.setLoadingMinTime(1000);
        worksPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, worksListView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageIndex = 1;
                loadWorks(pageIndex, pageSize);
            }
        });

        worksContainer = (LoadMoreListViewContainer) rootView.findViewById(R.id.container_work);
        worksContainer.useDefaultHeader();
        worksContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                //加载更多操作
                pageIndex++;
                loadWorks(pageIndex, pageSize);
            }
        });
        loadWorks(pageIndex, pageSize);
    }


    private void loadWorks(final int pIndex, int pSize) {
        AVQuery query = AVQuery.getQuery("LikeWork");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.limit(pSize);
        query.skip((pIndex - 1) * pSize);
        query.whereEqualTo("user", AVUser.getCurrentUser());
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (list != null && !list.isEmpty()) {
                    if (pageIndex == 1) {
                        worksPtrFrameLayout.refreshComplete();
                        works.clear();
                        worksObjs.clear();
                    }

                    List<Integer> workIds = new ArrayList<>();
                    for (AVObject avObj : list) {
                        workIds.add(avObj.getInt("workId"));
                        worksObjs.put(avObj.getInt("workId"), avObj);
                    }

                    works.addAll(new WorksDao(getContext()).getLikeWorks(workIds));
                    worksAdapter.notifyDataSetChanged();
                    worksContainer.loadMoreFinish(false, true);
                } else {
                    pageIndex--;
                    worksContainer.loadMoreFinish(false, false);
                }
            }
        });
    }

    class WorksAdapter extends BaseAdapter {


        private List<Works> data;

        public WorksAdapter(List<Works> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            WorksViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_like_work_item, parent, false);
                holder = new WorksViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (WorksViewHolder) convertView.getTag();
            }

            final Works works = data.get(position);
            holder.worksTitle.setText(works.getTitle());
            holder.worksDesc.setText(works.getCompress_content());
            holder.worksAuthor.setText("[" + works.getDynasty() + "] " + works.getAuthor());

            if (isDelMode) {
                holder.delBtn.setVisibility(View.VISIBLE);
                holder.delBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        worksObjs.get(works.getId()).deleteInBackground(new DeleteCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    data.remove(position);
                                    notifyDataSetChanged();
                                } else {
                                    Toast.makeText(getContext(), "删除失败，请重试", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
            } else {
                holder.delBtn.setVisibility(View.GONE);
            }

            return convertView;
        }

        public void showDelMode() {
            isDelMode = true;
            notifyDataSetChanged();
        }

        public void hideDelMode() {
            isDelMode = false;
            notifyDataSetChanged();
        }

        class WorksViewHolder {
            ImageView delBtn;
            TextView worksTitle;
            TextView worksDesc;
            TextView worksAuthor;

            public WorksViewHolder(View itemView) {
                worksTitle = (TextView) itemView.findViewById(R.id.tv_title);
                worksDesc = (TextView) itemView.findViewById(R.id.tv_desc);
                worksAuthor = (TextView) itemView.findViewById(R.id.tv_author);
                delBtn = (ImageView) itemView.findViewById(R.id.del_btn);
            }
        }
    }
}
